import pygame
import sys
import random
from constants import SCREEN_HEIGHT, SCREEN_WIDTH, DFSPAN_A, DFSPAN_B
import time
from load import bgm, enemies, players, Block, dead_info, Info


is_play_sound = False
time_span = random.uniform(DFSPAN_A, DFSPAN_B)
game_over = False
last_time = time.time()
score = 0


# 主程序
class Game:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
        self.clock = pygame.time.Clock()

    def run(self):
        running = True
        global last_time, time_span, game_over, is_play_sound, score
        while running:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
            bgm.play()
            current_time = time.time()
            if current_time - last_time >= time_span:
                enemies.add(Block())
                last_time = current_time
                time_span = random.uniform(DFSPAN_A, DFSPAN_B)
            self.screen.fill((255, 255, 255))
            collisions = pygame.sprite.groupcollide(players, enemies, False, False)
            if not collisions:
                players.update()
                enemies.update()
                for i in enemies:
                    if i.rect.right <= 0:
                        enemies.remove(i)
                        score += 1
                        print(score)
            else:
                print(f'game over,your score is {score}')
                if not is_play_sound:
                    pygame.mixer.Sound('reserve/sound/sound_dead.WAV').play()
                    is_play_sound = True
                self.screen.blit(dead_info.text_surface, dead_info.display())
            players.draw(self.screen)
            enemies.draw(self.screen)
            self.screen.blit(Info(f'Your score:{score}', None,
                                  36, (0, 0, 0),
                                  (255, 255, 255), (80, 25)).text_surface,
                             Info(f'Your score:{score}', None, 36, (0, 0, 0),
                                  (255, 255, 255), (80, 25)).display())
            pygame.display.flip()
            self.clock.tick(160)

        pygame.quit()
        sys.exit()